package cn.wolfcode.p2p.hosting.util;

import cn.wolfcode.p2p.base.exception.CustomerException;
import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 托管接入工具
 */
public class HostingUtil {

    /**
     * 商户号
     */
    public static final String PARTNER_ID= "200004595271";
    /**
     * 编码
     */
    public static final String INPUT_CHARSET= "utf-8";
    /**
     * 签名类型
     */
    public static final String SIGN_TYPE= "RSA";
    /**
     * 签名版本
     */
    public static final String SIGN_VERSION= "1.0";

    /**
     * 签名私钥
     */
    public static final String SIGN_PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJJqxunyHgxWN2aTSZp2jAYTOwGDeuS/Dkolk3g6/svnhVYAYn8iyjJ5Fo6YQcCz3F1+3YGjq1I1mIKRi3GaRoN3859vuCdo9nWFowF7BgepNSoGZY7uyYVc6EO3+TdeAlvdCceEng/a3hRoDcjLbsXdV9KwSfoCzdoRegy+yGf1AgMBAAECgYAHaRoaOyPkMfTp3yiJhdh+cji5UeNFcpoRjKdTHYFJ5rTr7mcN0j/zoAdRPkmNrEzJ+qLRbew84/ONIDqzjEBnUMRyWbq9rCr/yodld6uY8yQvXONGukv0mDArnsB+0HswkZ4oIMdHyw8EiCjcO+nBE63nc3ejw9XjBjwuUP/PwQJBAPtwxlwu9ORvn5LInQx/xEw6LWRn1kHuzU2V8QPuaZ1u/0MJ0Z1MqtEdWd4cUkox5etxpjAK8Ok7XUgfwcPdEjECQQCVEnep8vpDBxvokuz0bHARzGjUuZpMysBiTmbaUEwsAeCDj+rfQohISCF7GEDOargqKdlZ9XeBU5kZ/PEhf50FAkEA4r9/0o/x/rN/ByLtJeFux4NLfhl6Cblt4YLPd8kf6362qeEH7D/AZ5Z9faSyvQAkpN+3i+nB+cK0S59/4L7TcQJAeedtNew93Xw9xVYJMeRPTS7Ed1kEJlITOxD0KQlLER3D1LJnFoXY3osl3fy6WlKJIemxFVCXlomfhNIE+ijaZQJBANIxZSIC1qD9CA/RzPgxvpu0tjBN0u8Gak4lnUKtmBoBAyILoKkJ4ctElwqCpG4SAMLz6keWUYTUxXjrsR9sXiE=";
    /**
     * 签名公钥
     */
    public static final String SIGN_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCSasbp8h4MVjdmk0madowGEzsBg3rkvw5KJZN4Ov7L54VWAGJ/IsoyeRaOmEHAs9xdft2Bo6tSNZiCkYtxmkaDd/Ofb7gnaPZ1haMBewYHqTUqBmWO7smFXOhDt/k3XgJb3QnHhJ4P2t4UaA3Iy27F3VfSsEn6As3aEXoMvshn9QIDAQAB";

    /**
     * 敏感字加密公钥
     */
    public static final String ENCODE_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCDWwzhCg0z68cPPsEWBBsMQhHakIhd1uY5pwKZJU8PfSNtzrVgb6shzaKIu9mo72odS0dYIjgMEqopsUFYT95UCQq7/ob4zw29RKs+eDjMybCEuDLG1s1uPi+3nlurEIJg9sUWveb8GIyTOrE6m11qceRwgBNptRk0e1YTRvu9fwIDAQAB";

    /**
     * 会员接口地址
     */
    public static final String URL_MGS = "http://localhost:1111/mgs/gateway.do";

    /**
     * 收单接口地址
     */
    public static final String URL_MAS = "http://localhost:1111/mas/gateway.do";

    /**
     * 获取基本参数
     */
    public static Map<String,String> getBaseParams(){
        Map<String,String> map = new HashMap<String,String>() ;
        map.put("version" , "1.0") ;
        map.put("request_time" , getTimeString()) ;
        map.put("partner_id" , PARTNER_ID) ;
        map.put("_input_charset" , INPUT_CHARSET) ;
        map.put("sign_type" , SIGN_TYPE) ;
        map.put("sign_version" , SIGN_VERSION) ;
        return map;
    }


    public static String getTimeString(){
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        return format.format(new Date());
    }

    /**
     * 根据loginInfo 获取托管账户id
     */
    public static String getHostingIdentityId(Long id){
        return "wolfcode_"+id;
    }

    /**
     * 负责发送请求,拿到 字符串的结果即可
     */
    public static String requestHandlerToString(Map<String,String> paramMap,boolean isMgs){
        try {
            //2.做参数签名,把签名后的结果设置到基本参数 sign 中
            String signString = Tools.createLinkString(paramMap,false,true);

            String sign = SignUtil.sign(signString, HostingUtil.SIGN_TYPE, HostingUtil.SIGN_PRIVATE_KEY, HostingUtil.INPUT_CHARSET);
            paramMap.put("sign",sign);

            //拼接请求参数
            String requestParamString = Tools.createLinkString(paramMap,true,false);

            //3.发送接口请求
            //{"response_code":"APPLY_SUCCESS",
            // "partner_id":"200004595271",
            // "response_message":"%E6%8F%90%E4%BA%A4%E6%88%90%E5%8A%9F",
            // "sign_version":"1.0","_input_charset":"UTF-8",
            // "sign":"",
            // "response_time":"20181031101112",
            // "sign_type":"RSA"}

            String url = isMgs?URL_MGS:URL_MAS;

            String result = CallServiceUtil.sendPost(url,requestParamString);

            //4.接收返回结果,执行回签
            //把响应的数据进行 URLEncoder 解密
            result = URLDecoder.decode(result, HostingUtil.INPUT_CHARSET) ;
            System.out.println(result);
            return result;
        } catch (CustomerException e) {
            throw new CustomerException(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomerException("系统异常啦");
        }
    }


    /**
     * 调用  requestHandlerToString 的请求拿到字符串结果,转json做处理
     */
    public static Map<String,String> requestHandler(Map<String,String> paramMap){
        return requestHandler( paramMap,true) ;
    }
    /**
     * 调用  requestHandlerToString 的请求拿到字符串结果,转json做处理
     */
    public static Map<String,String> requestHandler(Map<String,String> paramMap,boolean isMgs){
        try {

            //托管请求
            String result = requestHandlerToString(paramMap,isMgs);

            //把响应的json字符串,转成map
            Map<String,String> map = JSON.parseObject(result,Map.class);

            if(!map.get("response_code").equals("APPLY_SUCCESS")){
                throw new CustomerException(map.get("response_message"));
            }

            checkSign(map);

            return map;
        } catch (CustomerException e) {
            throw new CustomerException(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomerException("系统异常啦");
        }
    }

    public static void checkSign(Map<String,String> map){
        try {
            //然后调用 Tools.createLinkString 拼接回签字符串
            String callBackSignString = Tools.createLinkString(map,false,true);

            String callBackSign = map.get("sign");
            //执行回签
            boolean checkSign = false;
            checkSign = SignUtil.Check_sign(callBackSignString,callBackSign, HostingUtil.SIGN_TYPE, HostingUtil.SIGN_PUBLIC_KEY, HostingUtil.INPUT_CHARSET);
            if(!checkSign){
                throw new CustomerException("回签失败");
            }
        } catch (CustomerException e) {
            throw new CustomerException(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 敏感字段加密
     */
    public static String endcodeString(String string){
        try {
            /**
             * 1.把待转换成指定字符集的二进制数据：Byte(account_name, _input_charset)；
             2.使用钱包的公钥对结果进加密码: RSA.encrypt(byte[],钱包公钥)；
             3.对加密后的数据二进制作base64 字符传换: Base64.encode(RSA(byte[],钱包公钥))；
             */
            byte[]  bytes = new byte[0];
            bytes = string.getBytes(HostingUtil.INPUT_CHARSET);
            bytes = RSA.encryptByPublicKey(bytes, HostingUtil.ENCODE_PUBLIC_KEY);
            String enString = Base64.encode(bytes);
            return enString;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return string;
    }


    /**
     * 把请求对象中的数据封装成map
     */
    public static Map<String,String> requestToMap(HttpServletRequest  request){
        Enumeration<String> names = request.getParameterNames();
        Map<String,String> paramMap = new HashMap<String,String>() ;
        while (names.hasMoreElements()){
            String name = names.nextElement();
            String value = request.getParameter(name) ;
            paramMap.put(name,value) ;
        }
        System.out.println(paramMap);
        return paramMap ;
    }
}
